mui.init()
var mask = mui.createMask(callback); //callback为用户点击蒙版时自动执行的回调；
var swith = false
var shares = null;
mui.previewImage();

function updateSerivces() {
	plus.share.getServices(function(s) {
		shares = {};
		for(var i in s) {
			var t = s[i];
			shares[t.id] = t;
		}
	}, function(e) {
		common.toast('获取分享服务列表失败：' + e.message);
	});
}
var slideNumber = 0
Vue.use(VueLazyload, {
	preLoad: 1.3,
	error: '../../images/loadImg/advert_one_max.png',
	loading: '../../images/loadImg/advert_one_max.png'
});
var details = new Vue({
	el: '#details',
	data: {
		imgCommonUrl: common.imageUrl,
		//轮播图
		sliders: [],
		footerSliders: '',
		num: 1,
		prod: '',
		shopDetail: '',
		allCount: 0,
		//参数
		prodParams: [],
		//选择规格
		checkSpec: '',
		showSelect: false,
		//		评论内容
		commintMain: [],
		prodCommCategory: '',
		curPage: 1,
		check: 1,
		commentSwith: false,
		noData: false,
		preload: '',
		//分享弹窗
		shareAlert: false,
		shareList: [],
		filePath: [],
		shareObj: ''

	},
	methods: {
		standard: function() {
			mask.show()
			this.showSelect = true
		},
		//		加减
		reduceShop: function(data) {
			if(data.num > 0) {
				data.num--
			}
		},
		inputNum: function(data) {
			data.num = data.num.replace(/[^0-9]/g, '')
			if(data.num > data.stocks) {
				data.num = data.stocks
				common.toast("库存不足")
			} else if(data.num <= 0 && data.num != '') {
				data.num = 0
			}
		},
		addShop: function(data) {
			if(data.num < data.stocks) {
				data.num++
			} else {
				data.num = data.stocks
				common.toast("库存不足")
			}
		},
		commentCheck: function(num, check) {
			if(this.check == num) {
				return
			} else if(check == 0) {
				common.toast('暂无评论')
				return
			}
			details.noData = false
			this.check = num
			this.commintMain = []
			this.curPage = 1
			comments()
		},
		//		点击添加到购物车
		addShopBuy: function() {

			if(!JSON.parse(localStorage.getItem('userData'))) {
				//商店信息
				var shopDetail = details.shopDetail
				local(shopDetail)
			} else {
				var temp = ''
				for(var i = 0; i < this.prod.skuDtoList.length; i++) {
					if(this.prod.skuDtoList[i].num > 0) {
						temp += this.prod.skuDtoList[i].skuId + ':' + this.prod.skuDtoList[i].num + ','
						this.allCount += this.prod.skuDtoList[i].num
					}
				}
				if(temp == '') {
					common.toast('请选择商品')
					return
				}
				common.ajax('/shopCart/addShopBuy', {
					prodId: details.preload,
					skuId: temp.substring(0, temp.length - 1)
				}, function(data) {
					if(data.code == 1) {
						for(var i = 0; i < details.prod.skuDtoList.length; i++) {
							details.prod.skuDtoList[i].stocks -= details.prod.skuDtoList[i].num
							//							details.prod.skuDtoList[i].num = 0
						}
						//						details.checkSpec.num = 0
						common.toast('添加成功')
						if(plus.webview.getWebviewById('shopping.html')) {
							plus.webview.getWebviewById('shopping.html').reload()
						}
					} else {
						if(data.resultMsg) {
							common.toast(data.resultMsg)
						}
					}
				})

			}
		},
		//跳到购物车业
		goshoppingcar: function() {
			var list = plus.webview.getWebviewById("ylindex.html")
			mui.fire(list, 'shopping');

			var wvs, self, launch;
			wvs = plus.webview.all();
			self = plus.webview.currentWebview();
			launch = plus.webview.getLaunchWebview();
			for(var i = 0, len = wvs.length; i < len; i++) {
				if(wvs[i].getURL() == launch.getURL() || wvs[i].id == 'ylindex.html' || wvs[i].id == 'home.html' || wvs[i].id == 'classify.html' || wvs[i].id == 'special.html' || wvs[i].id == 'shopping.html' || wvs[i].id == 'my.html' || wvs[i].id == '../special/specialregion.html') {
					continue;
				}
				wvs[i].close();
			}
		},
		//收藏
		addInterest: function() {
			common.ajax('/product/addInterest', {
				prodId: details.preload
			}, function(data) {
				if(data.code == 1) {
					details.prod.existsFavorite = !details.prod.existsFavorite
				} else {
					if(data.resultMsg) {
						common.toast(data.resultMsg)
					}
				}
			}, true)
		},
		//评论点赞
		usefulCounts: function(commintMain) {
			common.ajax('/product/updateUsefulCounts', {
				prodComId: commintMain.id
			}, function(data) {
				if(data.code == 1) {
					commintMain.usefulCounts++
				} else {
					if(data.resultMsg) {
						common.toast(data.resultMsg)
					}
				}
			}, true)

		},
		//立即购买
		goConfirm: function() {
			if(!JSON.parse(localStorage.getItem('userData'))) {
				common.open('../login/login.html', '../login/login.html')
				return
			}
			var temp = ''
			for(var i = 0; i < this.prod.skuDtoList.length; i++) {
				if(this.prod.skuDtoList[i].num > 0) {
					temp += this.prod.skuDtoList[i].skuId + ':' + this.prod.skuDtoList[i].num + ','
				}
			}
			if(temp == '') {
				common.toast('请选择商品')
				return
			}
			var data = {
				prodId: details.preload,
				skuIds: temp.substring(0, temp.length - 1)
			}
			common.open('../order/confirmorder.html', '../order/confirmorder.html', {
				swith: true,
				data: data
			})
		},
		//客服
		serviceCenter: function() {
			//			if(!banner.jumpUrl) {
			//				return
			//			}
			mui.openWindow({
				id: "../mask/nesting.html",
				url: '../mask/nesting.html',
				extras: {
					url: 'http://p.qiao.baidu.com/cps/chat?siteId=11390067&userId=24711168'
				}
			});
		},
		goshop: function() {
			if(plus.webview.getWebviewById('shop.html')) {
				if(!swith) {
					if(plus.webview.getWebviewById('../seach/shopSeach.html')) {
						plus.webview.getWebviewById('../seach/shopSeach.html').close()
					}
					mui.back()
				}
			} else {
				swith = true
				common.open("shop.html", "shop.html", details.shopDetail.shopId)
			}
		},
		//分享事件
		//获取分享列表
		shareSystem: function() {
			var shareBts = [];
			// 更新分享列表
			var ss = shares['weixin'];
			ss && ss.nativeClient && (shareBts.push({
					title: '微信朋友圈',
					s: ss,
					x: 'WXSceneTimeline',
					img: '../../images/penyouquan.png'
				}),
				shareBts.push({
					title: '微信好友',
					s: ss,
					x: 'WXSceneSession',
					img: '../../images/weixin.png'
				}));
			ss = shares['qq'];
			ss && ss.nativeClient && shareBts.push({
				title: 'QQ',
				s: ss,
				img: '../../images/qq.png'
			});
			details.shareList = shareBts
			if(details.shareList.length <= 0) {
				common.toast('没有可分享的APP')
			} else {
				details.shareAlert = true

			}
		},
		shareListCheck: function(data) {
			if(!data || !data.s) {
				common.toast('无效的分享服务！');
				return;
			}
			var msg = {
				extra: {
					scene: data.x
				}
			};
			msg.href = details.shareObj.shareUrl ? details.shareObj.shareUrl : 'http://www.dp218.com/';
			msg.title = details.shareObj.shareTitle;
			msg.content = details.shareObj.shareDes
			msg.thumbs = [details.imgCommonUrldetails + details.shareObj.sharePic];
			msg.pictures = [details.imgCommonUrldetails + details.shareObj.sharePic];
			//						if(data.s.authenticated) {
			data.s.send(msg, function() {
				details.shareAlert = false
				console.log('分享到"' + data.s.description + '"成功！');
			}, function(e) {
				details.shareAlert = false
				console.log('分享到"' + data.s.description + '"失败: ' + JSON.stringify(e));
			});
		}
	}
})
//轮播到第几张
document.querySelector('#slidersliders').addEventListener('slide', function(event) {
	details.num = event.detail.slideNumber + 1
});

$('.mui-content')[0].onscroll = function() {
	$(".mui-scroll").eq(slideNumber).height() < 200 ? $(".mui-control-content").css('min-height', 200) : $(".mui-control-content").css('min-height', $(".mui-scroll").eq(slideNumber).height())　
	if(slideNumber == 2) {
		var wScrollY = window.scrollY; // 当前滚动条位置    
		var wInnerH = window.innerHeight; // 设备窗口的高度（不会变）    
		var bScrollH = document.body.scrollHeight; // 滚动条总高度        
		if(wScrollY + wInnerH >= bScrollH) {
			if(details.commintMain.length <= 0 || details.noData) {
				return
			}
			comments()
		}
	}

}

function callback() {
	details.showSelect = false
}

mui.plusReady(function() {
	updateSerivces();
	var self = plus.webview.currentWebview();
	var id = self.parameter
	//var id = 5943
	details.preload = id
	document.querySelector('#slider').addEventListener('slide', function(event) {
		slideNumber = event.detail.slideNumber
		//参数和评论请求
		if(event.detail.slideNumber == 1 && details.prodParams.length == 0) {
			common.ajax('/product/queryDynamicParameter/' + id, {}, function(data) {
				if(data.code == 1) {
					details.prodParams = data.data.prodParams
					
					details.$nextTick(function() {
						$(".mui-scroll").eq(event.detail.slideNumber).height() < 200 ? $(".mui-control-content").css('min-height', 200) : $(".mui-control-content").css('min-height', $(".mui-scroll").eq(event.detail.slideNumber).height())
					})
				} else {
					if(data.resultMsg) {
						common.toast(data.resultMsg)
					}
				}
			}, true, 'get')
		} else if(event.detail.slideNumber == 2 && details.prodCommCategory == '') {
			comments()
		} else {
			$(".mui-scroll").eq(event.detail.slideNumber).height() < 200 ? $(".mui-control-content").css('min-height', 200) : $(".mui-control-content").css('min-height', $(".mui-scroll").eq(event.detail.slideNumber).height())

		}
	});
	common.ajax('/product/views/' + id, {}, function(data) {
		if(data.code == 1) {
			for(var i = 0; i < data.data.prod.prodPics.length; i++) {
				if(data.data.prod.prodPics.length - 1 > i) {
					details.sliders.push(data.data.prod.prodPics[i])
				} else {
					details.footerSliders = data.data.prod.prodPics[data.data.prod.prodPics.length - 1]
				}
			}
			
			details.shareObj = data.data.shareObj
			details.shopDetail = data.data.shopDetail
			details.allCount = data.data.allCount
			//默认选中
			for(var i = 0; i < data.data.prod.skuDtoList.length; i++) {
				if(data.data.prod.skuDtoList[i].skuId == data.data.prod.skuId) {
					data.data.prod.skuDtoList[i].num = 1
					details.checkSpec = data.data.prod.skuDtoList[i]
				} else {
					data.data.prod.skuDtoList[i].num = 0
				}
			}
			details.prod = data.data.prod
			details.$nextTick(function() {
				$(".mui-scroll").eq(slideNumber).height() < 200 ? $(".mui-control-content").css('min-height', 200) : $(".mui-control-content").css('min-height', $(".mui-scroll").eq(slideNumber).height())　
				$.each($(".details_img").find('img'), function(i, a) {
					$(".details_img").find('img').eq(i).attr({
						'data-preview-group': 'mian',
						'data-preview-src': ''
					})
				})
			})
		} else {
			if(data.resultMsg) {
				common.toast(data.resultMsg)
			}
		}
	}, true, 'get')
	//评论
	function comments() {
		if(details.commentSwith) {
			return
		}
		details.commentSwith = true
		var arr = ['all', 'good', 'medium', 'poor', 'photo']
		common.jsonAjax('/product/comments', {
			prodId: id,
			condition: arr[details.check - 1],
			curPageNO: details.curPage++
		}, function(data) {
			console.log(JSON.stringify(data))
			if(data.code == 1) {
				details.prodCommCategory = data.data.prodCommCategory
				for(var i = 0; i < data.data.list.length; i++) {
					data.data.list[i].photosImg = data.data.list[i].photos.split(',')
				}
				details.commintMain = details.commintMain.concat(data.data.list)
				console.log(details.commintMain)
				details.$nextTick(function() {
					$(".mui-scroll").eq(slideNumber).height() < 200 ? $(".mui-control-content").css('min-height', 200) : $(".mui-control-content").css('min-height', $(".mui-scroll").eq(slideNumber).height())　
				})
				if(data.data.curPageNO < details.curPage) {
					details.noData = true
				}
			} else {
				if(data.resultMsg) {
					common.toast(data.resultMsg)
				}
			}
			setTimeout(function() {
				details.commentSwith = false
			}, 100)
		}, true)
	}
	var close = mui.back
	mui.back = function() {
		if($(".select").hasClass('show')) {
			$(".select").removeClass('show')
			mask.close()
		} else {
			close()
		}
	}
})
//本地存储
function local(getShopName) {
	//店铺信息
	getShopName.shopName = getShopName.siteName
	getShopName.checkSts = 1
	getShopName.edit = 0
	getShopName.local = true

	getShopName.proId = details.preload

	//商品信息
	getShopName.cartItems = []
	var shopData = details.prod
	shopData.prodName = shopData.name
	shopData.local = true
	shopData.checkSts = 1
	shopData.edit = 0
	//规格
	var shopSpec = []
	for(var i = 0; i < shopData.skuDtoList.length; i++) {
		if(shopData.skuDtoList[i].num > 0) {
			shopData.skuDtoList[i].basketCount = shopData.skuDtoList[i].num
			shopData.skuDtoList[i].basketId = shopData.skuDtoList[i].skuId
			shopData.skuDtoList[i].promotionPrice = ''
			shopData.skuDtoList[i].checkSts = 1
			shopData.skuDtoList[i].edit = 0
			shopData.skuDtoList[i].local = true
			shopData.skuDtoList[i].cnProperties = shopData.skuDtoList[i].cn_properties
			shopSpec.push(shopData.skuDtoList[i])
		}
	}
	shopData.shopSpec = shopSpec
	getShopName.cartItems.push(shopData)
	var list = JSON.parse(localStorage.getItem('shopPingCar')) || []

	if(list.length <= 0) {
		list.push(getShopName)
	} else {
		var check = 0
		for(var i = 0; i < list.length; i++) {
			//判断店铺有没有相同，不同就push
			if(list[i].shopId == getShopName.shopId) {

				for(var j = 0; j < list[i].cartItems.length; j++) {
					//判断是否同一个商品，不同就添加在同店铺
					if(list[i].cartItems[j].skuId == details.prod.skuId) {
						for(var c = 0; c < list[i].cartItems[j].shopSpec.length; c++) {
							for(var a = 0; a < shopSpec.length; a++) {
								//判断同不同规格,同规格就加数量,否则就添加一个规格
								if(shopSpec[a].basketId == list[i].cartItems[j].shopSpec[c].basketId) {
									list[i].cartItems[j].shopSpec[c].basketCount = Number(list[i].cartItems[j].shopSpec[c].basketCount) + Number(shopSpec[a].num)
								} else {
									var basketId = '"basketId":' + shopSpec[a].basketId
									if(JSON.stringify(list).indexOf(basketId) < 0) {
										list[i].cartItems[j].shopSpec.push(shopSpec[a])
										shopSpec[a].num = 0
									}
								}
							}
						}
					} else {
						var skuId = '"skuId":' + details.prod.skuId
						if(JSON.stringify(list).indexOf(skuId) < 0) {
							list[i].cartItems.push(shopData)
							break
						}
					}
				}
			} else {
				var proId = '"shopId":' + getShopName.shopId
				if(JSON.stringify(list).indexOf(proId) < 0) {
					list.push(getShopName)
					break
				}
			}
		}
	}
	if(shopSpec.length > 0) {
		localStorage.setItem('shopPingCar', JSON.stringify(list))
		common.toast('添加成功')

		for(var i = 0; i < details.prod.skuDtoList.length; i++) {
			details.prod.skuDtoList[i].stocks -= details.prod.skuDtoList[i].num
			details.prod.skuDtoList[i].num = 0
		}
		if(plus.webview.getWebviewById('shopping.html')) {
			plus.webview.getWebviewById('shopping.html').reload()
		}
	} else {
		common.toast('请选择商品')
	}
}
var setheight = ''
if(mui.os.ios) {
	$(document).on('focus', 'input', function() {
		$(".show").addClass('showSwith')
		plus.webview.currentWebview().setStyle({
			top: '0',
			bottom: '40%'
		})
		setHe()
	})
	$(document).on('blur', 'input', function() {
		if(plus.device.model == 'iPhoneX') {
			plus.webview.currentWebview().setStyle({
				top: '0',
				bottom: "34px"
			})
		} else {
			plus.webview.currentWebview().setStyle({
				top: '0',
				bottom: '0'
			})
		}

		$(".show").removeClass('showSwith')
		setheight = setTimeout(setHe, 100)
	})

} else {
	var originalHeight = document.documentElement.clientHeight || document.body.clientHeight;
	window.onresize = function() {
		//软键盘弹起与隐藏  都会引起窗口的高度发生变化
		var resizeHeight = document.documentElement.clientHeight || document.body.clientHeight;
		if(resizeHeight * 1 < originalHeight * 1) { //resizeHeight<originalHeight证明窗口被挤压了
			$(".show").addClass('showSwith')
		} else {
			$(".show").removeClass('showSwith')
		}
	}
}

function setHe() {
	document.body.scrollTop = document.body.scrollHeight
	setheight = setTimeout(setHe, 100)
}

if(common.data && common.data.token) {
	var auth = {
		auth: "YL " + common.data.token
	}
}
//请求后台tokan过期问题
mui.ajax(common.urls + '/p/userhome', {
	data: {},
	dataType: 'json', //服务器返回json格式数据
	type: 'get', //HTTP请求类型
	timeout: 10000, //超时时间设置为10秒；
	headers: auth,
	success: function(data) {
		console.log(data)
		if(data.code == '-10') {
			localStorage.removeItem('userData')
		}
	}
});